package com.lck.main.view;

import com.lck.main.game.Chess;
import com.lck.main.game.ChessFactory;
import com.lck.main.model.Record;
import com.lck.main.model.MyMessage;
import com.lck.main.server.ClientReceiveThread;
import com.lck.main.server.ClientThread;
import com.lck.main.util.SocketUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.net.Socket;
import java.util.LinkedList;

public class GamePanel extends JPanel {

    private boolean isLocked = false;

    private String account;

    private String to;

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    private Socket socket;


    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public void setLocked(boolean locked) {
        isLocked = locked;
    }

    public Image getImage(String path){
        return Toolkit.getDefaultToolkit().getImage(path);
    }

    //定义一个保存所有棋子成员变量，类型是数组。
    private Chess[] chesses = new Chess[32];//保存所有棋子

    //悔棋
    private LinkedList<Record> huiqiList = new LinkedList();

    private Chess selectedChess;//当前选中的棋子。

    public void setCurPlayer(int curPlayer) {
        this.curPlayer = curPlayer;
    }

    private int curPlayer = 0;//记住当前阵营

    //提示的label
    private JLabel hintLabel;

    private GameFrame gameFrame;

    private MyMessage req;

    public void setGameFrame(GameFrame gameFrame) {
        this.gameFrame = gameFrame;
    }

    public Chess[] getChesses() {
        return chesses;
    }

    public void setChesses(Chess[] chesses) {
        this.chesses = chesses;
        repaint();
    }

    public void setHintLabel(JLabel hintLabel) {
        this.hintLabel = hintLabel;
    }

    /**
     * 实现悔棋功能
     */
    public void huiqi(){
        Record record = huiqiList.pollLast();
        //将操作的棋子的坐标修改回去
        record.getChess().setP(record.getStart());
        chesses[record.getChess().getIndex()] = record.getChess();
        if (record.getEatedChess()!=null){
            chesses[record.getEatedChess().getIndex()] = record.getEatedChess();
        }
//        curPlayer = record.getChess().getPlayer();
        overMyturn(record,null);
        //刷新棋盘
        repaint();
    }

    public void startReceive(){
        ClientReceiveThread crt = ClientReceiveThread.getInstance();
        crt.setListener(new ClientReceiveThread.ResponseListener() {
            @Override
            public void response(MyMessage resp) {
                Object content = resp.getContent();
                if (content instanceof Record){
                    Record record = (Record)content;
                    switch(resp.getType()){
                        case MOVE:
                            chesses[record.getChess().getIndex()] = record.getChess();
                            break;
                        case EAT:
                            //删除吃子
                            chesses[record.getEatedChess().getIndex()] = null;
                            chesses[record.getChess().getIndex()] = record.getChess();
                            break;
                        case PEACE:
                            System.out.println("GamePanel:::PEACE");
                            int result = JOptionPane.showConfirmDialog(null, "是否同意求和？", "求和", JOptionPane.YES_NO_OPTION);
                            req.setContent(new Record());
                            if (0 == result) {
                                //同意
                                req.setType(MyMessage.Type.PEACE_SUCCESS);
                                gameFrame.dispose();
                                new MainFrame();
                            } else {
                                //否
                                req.setType(MyMessage.Type.PEACE_FAILURE);
                            }
                            System.out.println(req);
                            SocketUtil.getInstance().send(req);
                            System.out.println("求和结束");
                            break;
                        default:
                            break;
                    }
                    //解锁棋盘
                    isLocked = false;
                    repaint();
                }
            }
        });
//        ClientThread crt = new ClientThread(socket, new ClientThread.ResponseListener() {
//            @Override
//            public void success(MyMessage resp) {
//                Object content = resp.getContent();
//                if (content instanceof Record){
//                    Record record = (Record)content;
//                    switch(resp.getType()){
//                        case MOVE:
//                            chesses[record.getChess().getIndex()] = record.getChess();
//                            break;
//                        case EAT:
//                            //删除吃子
//                            chesses[record.getEatedChess().getIndex()] = null;
//                            chesses[record.getChess().getIndex()] = record.getChess();
//                            break;
//                        default:
//                            break;
//                    }
//                    //解锁棋盘
//                    isLocked = false;
//                    repaint();
//                }
//            }
//        });
//        crt.start();
    }

    //构造方法
    public GamePanel(){
        req = SocketUtil.getInstance().getReq();
        System.out.println("GamePanel");
        createChesses();
//        startReceive();
        /**
         * 1.点击棋盘
         * 2.如何判断点击的地方是否有棋子对象
         * 3.如何区分重新选择，移动，吃子
         * -----
         * 棋盘规则
         * 1.不可操作对方的棋子
         * 2.一方走完之后另一方才能走
         */
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (isLocked){//如果棋盘被锁则点击无效。
                    return;
                }
                System.out.println("点击棋盘的坐标为:x=" + e.getX() + ",y=" + e.getY());
                Point p = Chess.getPointFromXY(e.getX(),e.getY());
                System.out.println("点击棋盘的网格坐标对象为:p===" + p);
//                Chess c = getChessByP(p);
                if (selectedChess == null){
                    //第一次选择
                    selectedChess = getChessByP(p);
                    if (selectedChess != null && selectedChess.getPlayer() != curPlayer){
                        hintLabel.setText("<html>选择错误<br/>"+ (curPlayer == 0?"红方走":"黑方走") +"</html>");
                        selectedChess = null;
                    }
                } else {
                    //重新选择，移动，吃子
                    Chess c = getChessByP(p);
                    if (c!=null){
                        //第n次点击的时候有棋子
                        //重新选择，吃子
                        if (c.getPlayer() == selectedChess.getPlayer()) {
                            //相同阵营重新选择
                            System.out.println("重新选择");
                            selectedChess = c;
                        }
                        else {
                            //吃子
                            System.out.println("吃子");
                            if (selectedChess.isAbleMoved(p,GamePanel.this)){
                                Record record = new Record();
                                record.setChess(selectedChess);
                                record.setStart(selectedChess.getP());
                                record.setEnd(p);
                                record.setEatedChess(c);
                                huiqiList.add(record);
                                //从数组中删除被吃掉的棋子
                                chesses[c.getIndex()] = null;
                                //修改要移动的棋子的坐标
                                selectedChess.setP(p);
                                req.setType(MyMessage.Type.EAT);
                                req.setContent(record);
                                overMyturn(record,req);
                            }

                        }
                    }else{
                        //第n次点击空白的地方。
                        //移动
                        System.out.println("移动");
                        if (selectedChess.isAbleMoved(p,GamePanel.this)){
                            Record record = new Record();
                            record.setChess(selectedChess);
                            record.setStart(selectedChess.getP());
                            record.setEnd(p);
                            record.setEatedChess(c);
                            huiqiList.add(record);
                            selectedChess.setP(p);
                            req.setType(MyMessage.Type.MOVE);
                            req.setContent(record);
                            overMyturn(record,req);
                        }
                    }
                }
                System.out.println("点击的棋子对象为:selectedChess===" + selectedChess);
                System.out.println("棋子记录集合数据====:" + huiqiList);
                //刷新棋盘，即重新执行paint方法
                repaint();

            }
        });
    }

    /**
     * 结束当前回合
     */
    private void overMyturn(Record record, MyMessage req){
        //发送消息给服务，回合结束
        //更新对方棋盘
        //解锁对手棋盘
        if (req != null){
            SocketUtil.getInstance().send(req);
        }
        //锁定自己的棋盘
        isLocked = true;
        //修改提示信息
//        curPlayer = curPlayer == 0 ? 1 :0;
        selectedChess = null;
        hintLabel.setText("红方走".equals(hintLabel.getText())?"黑方走":"红方走");
    }

    /**
     * 根据网格坐标p对象查找棋子对象
     * @param p
     * @return
     */
    public Chess getChessByP(Point p){
        for (Chess chess : chesses) {
            if (chess != null && chess.getP().equals(p)){
                    return chess;
            }
        }
        return null;
    }

    /**
     * 创建所有棋子
     */
    private void createChesses(){
        String [] names = {"che","ma","xiang","shi","boss","shi","xiang","ma","che","pao","pao","bing","bing","bing","bing","bing"};
        int [] xs = {1,2,3,4,5,6,7,8,9,2,8,1,3,5,7,9};
        for (int i = 0; i < names.length; i++) {
//            Chess c = new Che();//创建棋子对象
            //创建车
            Chess c = ChessFactory.create(names[i],0,xs[i]);
//            c.setName(names[i]);
//            c.setP(ps[i]);
//            c.setPlayer(0);
            c.setIndex(i);
            chesses[i] = c;
        }
        for (int i = 0; i < names.length; i++) {
//            Chess c = new Chess();//创建棋子对象
//            c.setName(names[i]);
//            c.setP(ps[i]);
//            c.setPlayer(1);
            Chess c = ChessFactory.create(names[i],1,xs[i]);
            c.reverse();
            c.setIndex(i+16);
            chesses[c.getIndex()] = c;

        }
    }

    /**
     * 绘制所有棋子
     */
    private void drawChesses(Graphics g){
        for(Chess chess: chesses){
            if (chess != null){
                chess.draw(g,this);
            }
        }
    }
    @Override
    public void paint(Graphics g) {
        System.out.println("paint");
//        super.paint(g);
        //1.准备图片路径
        String path = "pic"+ File.separator;
        //2.通过图片路径得到图片对象
        Image bgImg = getImage(path + "qipan.jpg");
        //3.将图片画到面板上
        g.drawImage(bgImg,0,0,this);

        //画棋子
        drawChesses(g);

        if (selectedChess != null){
            selectedChess.drawRect(g);
        }
    }
}
